//
//  RealmModel.m
//  lvfj
//
//  Created by lvfeijun on 2021/7/28.
//  Copyright © 2021 Goudu KuaiEx Technology(Shenzhen)Co.,ltd. All rights reserved.
//

#import "RealmModel.h"

@implementation RealmModel
#pragma mark 初始化
+ (void)migrationData
{
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
   // 27-4.3.0- TQ - 2019/08/20
    //4.4.0- TQ - 2019/12/28
    //30-4.6.0- sillker - 2020/04/22
    //31-4.7.1- tq - 2020/05/18
    //32-4.8.0- TQ - 2020/06/09
    //33-4.8.3- TQ - 2020/07/14
    //33-4.8.6- TQ - 2020/09/23
    //35-4.8.8- TQ - 2020/10/26
    //36-4.9.0- sillker - 2020/11/18
    //37-4.9.0- sillker - 2020/12/09
    //38-4.10.3 - yechu - 2021/6/9
    //40-5.0.0- yechu - 2021/6/9
    config.schemaVersion = 40;//版本号
    config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
        // 目前我们还未进行数据迁移，因此 oldSchemaVersion == 0
        if (oldSchemaVersion < 1) {
            // enumerateObjects:block: 方法遍历了存储在 Realm 文件中的每一个“Person”对象
            [migration enumerateObjects:HQKnowledgesModel.className
                                  block:^(RLMObject *oldObject, RLMObject *newObject) {
                                      
                                      // 将名字进行合并，存放在 fullName 域中
                                      newObject[@"qidKid"] = [NSString stringWithFormat:@"%@ %@",
                                                                oldObject[@"question_id"],oldObject[@"knowledge_id"]];
                                      
//                                      if (oldSchemaVersion<2) {
//
//                                      }
                                      
                                  }];
        }
        
        if (oldSchemaVersion < 2) {
        
            [migration enumerateObjects:HQQuestionHtmlParsedData.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"isBold"] = @(NO);
                newObject[@"color"]= @"0x000000";
            }];
        }
        
        if (oldSchemaVersion < 3) {
            
            [migration enumerateObjects:HQSaveKnowLedgeModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"extension"] = @"";
                
            }];
            [migration enumerateObjects:HQChapterListModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"extension"] = @"";
                
            }];
        }
        
        if (oldSchemaVersion < 4) {
            [migration enumerateObjects:HQLessonDetailModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                
            }];
            
            [migration enumerateObjects:HQVideoLogModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                
            }];
        }

        // 科目拉取改为科目组别名方式，需要重新进入科目管理
        if (oldSchemaVersion < 5) {
            kGVUserDefaults.hq_selectSecondCategoryID = 0;
            kGVUserDefaults.hq_selectSecondCategoryName = @"";
            [IntentionManager saveIntention:0 intentionName:@""];
            
            [migration deleteDataForClassName:HQCourseInitialListModel.className];
            [migration deleteDataForClassName:HQCourseInitialModel.className];

            [migration enumerateObjects:HQBoxChapterDataVersionModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"serverVersion"] = @"";
                newObject[@"localVersion"] = @"";
                
            }];
        }

        // 公告增加sort字段
        if (oldSchemaVersion < 6) {
            [migration enumerateObjects:HQAnnouncementModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"sort"] = @(0);
            }];
        }
        
        if (oldSchemaVersion < 7) {
            [migration enumerateObjects:HQGoodsDetailsModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
            }];
        }
        
        if (oldSchemaVersion < 8) {
            [migration enumerateObjects:HQCategoriesCommonModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
            }];
        }
        
        if (oldSchemaVersion < 9) {
            [migration enumerateObjects:HQCategoriesCommonModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
            }];
        }
//        if (oldSchemaVersion <10) {
//            [migration enumerateObjects:HQLoginModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
//            }];
//        }
        if (oldSchemaVersion < 11) {
            //3.2.0 模型修改
            [migration enumerateObjects:HQRecommendDetailModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                NSString *oldGoodsId = oldObject[@"goodsId"];
                newObject[@"goodsId"] = @(oldGoodsId.longLongValue);
                newObject[@"groupId"] = @0;
                newObject[@"idoneityPersons"] = @"";
            }];
        } if (oldSchemaVersion < 12) {
            //3.2.0 模型增加
            [migration enumerateObjects:HQContinueLastModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"useedTime"] = @0;
                newObject[@"startTime"] = @0;
            }];
        } if (oldSchemaVersion < 13) {
            //3.2.0 模型增加
            [migration enumerateObjects:HQPaperModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"product_info"] = [ProductInfo new];
            }];
        } if (oldSchemaVersion < 14) {
            //移除HQHomeworkAnswerInfo
            DDLogDebug(@"移除HQHomeworkAnswerInfo");
            
        }
//        if (oldSchemaVersion <15) {
//            //3.4
//            [migration enumerateObjects:PushData.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
//                newObject[@"msgType"] = @-1;
//                newObject[@"msgTitle"] = @"";
//                newObject[@"msgRedirect"] = @"";
//                newObject[@"msgContent"] = @"";
//                newObject[@"msgShareImg"] = @"";
//                newObject[@"msgShareContent"] = @"";
//                newObject[@"time"] = @0;
//            }];
//
//        }
        if (oldSchemaVersion <16) {
            //3.5
            [migration enumerateObjects:HQAdModels.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
              newObject[@"homeWindowAD"] =  [[RLMArray<HQAdModel> alloc] initWithObjectClassName:[HQAdModel className]];
            }];
        } if (oldSchemaVersion <17) {
            //3.6
            [migration enumerateObjects:HQCategoriesCommonModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"alias"] =  @"";
            }];
            
        } if (oldSchemaVersion <18) {
            //3.6
            [migration enumerateObjects:HQCourseInitialModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"alias"] =  @"";
            }];
        } if (oldSchemaVersion <19) {
          //部分数据模型删除
            DDLogDebug(@"部分数据模型删除");
            
        } if (oldSchemaVersion <20) {
            //  3.6
            [migration enumerateObjects:HQCommentItem.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"commentReply"] = @"";
                newObject[@"commentPic1"] =  @"";
                newObject[@"commentPic2"] =  @"";
                newObject[@"commentPic3"] =  @"";
            }];
        } if (oldSchemaVersion <21) {
            //3.6 标签排序
            [migration enumerateObjects:HQCourseInitialModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"order_tag"] =  @-1;
            }];
        }
        if (oldSchemaVersion <22) {
            //3.6 标签排序
            [migration enumerateObjects:HQRecommendDetailModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"startTime"] =  @0;
                newObject[@"endTime"] =  @0;
                newObject[@"shareImg"] =  @"";
                newObject[@"remark"] =  @"";
                
                newObject[@"marketingOpt"] =  @0;
                newObject[@"purchaser"] =  @0;
                newObject[@"stock"] =  @0;

            }];
        }
        
        if (oldSchemaVersion <23) {
            //3.8.0 扫码查看解析banner
            [migration enumerateObjects:HQAdModels.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"QRAnalysisAD"] =  [[RLMArray<HQAdModel> alloc] initWithObjectClassName:[HQAdModel className]];
            }];
            [migration enumerateObjects:HQKnowledgeDetail.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"second_category"] = @(0);
                newObject[@"category_id"] = @(0);
                newObject[@"category_name"] = @"";
            }];
        }
       
        if (oldSchemaVersion < 24) {
            [migration enumerateObjects:HQChapterListModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"right_percent"] = @(0);
            }];
            
        }
        
        if (oldSchemaVersion < 25) {
            [migration enumerateObjects:HQAdModels.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"examId"] = @0;
            }];
        }
        
        if (oldSchemaVersion < 26) {
            [migration enumerateObjects:HQActivityCourseListModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"classList"] =  [[RLMArray<HQRecommendGoodsGroupListModel> alloc] initWithObjectClassName:[HQRecommendGoodsGroupListModel className]];
            }];
        }
        
        if (oldSchemaVersion < 27) {
            [migration enumerateObjects:HQSaveChapterModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"right_percent"] = @0;
            }];
        }
        
//        if (oldSchemaVersion < 31) {
//            [migration enumerateObjects:GetShareInfoModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
//                newObject[@"roomId"] = @0;
//            }];
//        }
        
        if (oldSchemaVersion < 29) {
            [migration enumerateObjects:HQLessonDetailModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"hd_url"] = @"";
                newObject[@"md_url"] = @"";
                newObject[@"sd_url"] = @"";
                newObject[@"has_comment"] = @(NO);
                newObject[@"is_prelisten"] = @(NO);
                newObject[@"resource"] = @(0);
                newObject[@"paragraphs"] = nil;
            }];
            
            [migration enumerateObjects:HQVideoLogModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"willSentToServerLen"] = @0;
                newObject[@"type"] = @0;
                newObject[@"title"] = @"";
                newObject[@"latestCourseType"] = @0;
                newObject[@"latestLessionType"] = @0;
                newObject[@"latestCourseResource"] = @0;
                newObject[@"startTime"] = @0;
                newObject[@"tutorType"] = @0;
                newObject[@"videoSrc"] = @0;
                newObject[@"isLocalPlay"] = @0;
                newObject[@"goodsId"] = @0;
                newObject[@"productName"] = @"";
                newObject[@"categoryId"] = @0;
                newObject[@"start_position"] = @0;
                newObject[@"duration"] = @0;
                newObject[@"classes"] = @"";
                
            }];
            
            
            [migration enumerateObjects:UserMaterialModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"useType"] = @0;
                newObject[@"isCanShare"] = @(NO);
            }];
            
            [migration enumerateObjects:HQUserPaperRecord.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"num"] = @0;
                newObject[@"right_count"]= @0;
            }];
            
//            [migration enumerateObjects:GoodsGroupDetailsModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
//                newObject[@"isNewGift"] = @0;
//            }];
//
//            [migration enumerateObjects:PinTuanGroupsGoodsModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
//                newObject[@"service"] = nil;
//                newObject[@"giftList"] = nil;
//            }];
        }
        
        if (oldSchemaVersion <30) {
            [migration enumerateObjects:HQSaveKnowLedgeModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"right_percent"] =  @0;
            }];
        }
        
        if (oldSchemaVersion < 32) {
            [migration enumerateObjects:AdvertisementPictureModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"title"] =  @"";
            }];
            
            [migration enumerateObjects:HQBookedLiveModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"isFree"]   = @0;
                newObject[@"lessonId"] = @0;
                oldObject[@"sid"]      = @0;
                oldObject[@"topId"]    = @0;
            }];
        }
        if (oldSchemaVersion < 33) {
            [migration enumerateObjects:Payload.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"ext"] = @"";
                newObject[@"msgId"] = @0;
            }];
        }
        
        if (oldSchemaVersion < 36) {
            [migration enumerateObjects:GetShareInfoModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"liveId"] = @0;
            }];
        }
        
        if (oldSchemaVersion < 37) {
            [migration enumerateObjects:HQCategoryModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"openState"] = @0;
            }];
        }
        
        if (oldSchemaVersion < 40) {
            [migration enumerateObjects:HQUserConfigData.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"questionView_memory"] = @0;
            }];
            
            // 5.0.0- huijun - 2021/5/11
            [migration enumerateObjects:HQExerciseInfo.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"paper_id"] = @0;
            }];
            
            [migration enumerateObjects:HQHomeworkQuestionOverviewAnswerDetail.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"mark_score"] = @-1;
                newObject[@"is_mark"] = @(NO);
            }];
            
            [migration enumerateObjects:HQChapterListModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"isKnowledge"] = @(NO);
            }];
            
            [migration enumerateObjects:HQContinueLastModel.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"paperDetail"] = [HQPaperDetailModel new];
            }];
            
            [migration enumerateObjects:HQQuestionInfo.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                newObject[@"app_report_state"] = @-1;
            }];
        }
    };
    [RLMRealmConfiguration setDefaultConfiguration:config];
}
// 设置用户对于数据库名
- (void)initForUserId:(NSString *)userId {
    if (timer) {
        [self clearData];
    }
    
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
    
    NSURL *pathURL = [config.fileURL URLByDeletingLastPathComponent];
    if (![pathURL.path hasSuffix:@"/realm"]) {
        pathURL = [pathURL URLByAppendingPathComponent:@"realm"];
    }
    NSFileManager *manger = [NSFileManager defaultManager];
    if (![manger fileExistsAtPath:pathURL.path]) {
        NSError *error = nil;
        [manger createDirectoryAtURL:pathURL withIntermediateDirectories:YES attributes:nil error:&error];
        if (error) {
            BNIMDataLog(@"%@",error.description);
        }
    }
    // 设置对应数据库
    config.fileURL = [[pathURL URLByAppendingPathComponent:userId] URLByAppendingPathExtension:@"realm"];
    
    
    
    // 是否需要升级
    // 设置新的架构版本。这个版本号必须高于之前所用的版本号（如果您之前从未设置过架构版本，那么这个版本号设置为 0）
    config.schemaVersion = 17;
    
    // 设置闭包，这个闭包将会在打开低于上面所设置版本号的 Realm 数据库的时候被自动调用
    config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
    //        // 目前我们还未进行数据迁移，因此 oldSchemaVersion == 0
    //
    //        NSLog(@"===================== %d", oldSchemaVersion);
    //        if (oldSchemaVersion < 6) {
    //            // 什么都不要做！Realm 会自行检测新增和需要移除的属性，然后自动更新硬盘上的数据库架构
    //            NSLog(@"00000");
    //            [migration enumerateObjects:IMModel.className
    //                                  block:^(RLMObject *oldObject, RLMObject *newObject) {
    //
    //            // 将两个 name 合并到 fullName 当中
    //            newObject[@"ppl2"] = @2;
    //            }];
    //        } else {
    //            NSLog(@"111111");
    //        }
    };
    
    // 若不是增量，考虑删除所有数据，甚至db文件
    //    //删除表中所有的数据
    //    [realm transactionWithBlock:^{
    //        [realm deleteAllObjects];
    //    }];
    
    
    // 获取 Realm 文件的父目录
    NSString *folderPath = config.fileURL.URLByDeletingLastPathComponent.path;
    // 禁用此目录的文件保护
    [[NSFileManager defaultManager] setAttributes:@{NSFileProtectionKey: NSFileProtectionNone}
                                     ofItemAtPath:folderPath error:nil];
    
    [RLMRealmConfiguration setDefaultConfiguration:config];
    
    //创建用户文件夹
//    [self initCreateUserFilePath];
    [[PLIMFileManager manager] initCreateUserFilePath:[IMCentre get_user_id]];
    
    // 清除已删除数据
    [self delNoUseData];
    
    [self startTime];
    [[ReadManager Share] initRead];
}


#pragma mark 属性设置
// 设置唯一健
+ (NSString *)primaryKey {
    return @"msid";
}

////设置属性默认值
+ (NSDictionary *)defaultPropertyValues{
    return @{@"mid":@"",
             @"readList":@"",
             @"createTime":@0,
             @"updateTime":@0,
             @"msgStatus":@0,
             @"atCount":@0,
             @"option_list": [[RLMArray alloc] initWithObjectClassName:[OptionItem className]]
             
    };
}

//设置忽略属性,即不存到realm数据库中
+ (NSArray<NSString *> *)ignoredProperties {
    return @[@"toBody", @"exceptionMsg", @"groupHead", @"readMsgList",@"groupMember",@"msgFid",@"msidList",@"userIdList",@"top",@"disturb",@"cellHeight",@"group"];
}
//用于copy
- (id)copyWithZone:(NSZone *)zone
{
    RealmModel *obj = [RealmModel allocWithZone:zone];
    obj.mid = self.mid
    obj.createTime = self.createTime;
    return obj;
}
////一般来说,属性为nil的话realm会抛出异常,但是如果实现了这个方法的话,就只有name为nil会抛出异常,也就是说现在cover属性可以为空了
//+ (NSArray *)requiredProperties {
//    return @[@"name"];
//}
//
////设置索引,可以加快检索的速度
//+ (NSArray *)indexedProperties {
//    return @[@"ID"];
//}
@end

@implementation HQQT_PDFMaterialsModel
- (id)copyWithZone:(NSZone *)zone
{
    HQQT_PDFMaterialsModel *model = HQQT_PDFMaterialsModel.new;
    model.name = self.name;
    model.id = self.id;
    model.useType = self.useType;
    
    model.downloadUrl = self.downloadUrl;
    model.fileName = self.fileName;
    model.fileFormat = self.fileFormat;
    model.size = self.size;
    model.url = self.url;
    return model;
}
@end
